import { Injectable } from '@nestjs/common';
import * as qiniu from 'qiniu';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class QiniuService {
  private mac: qiniu.auth.digest.Mac;
  private config: qiniu.conf.Config;
  private bucketManager: qiniu.rs.BucketManager;

  constructor(private readonly configService: ConfigService) {
    const accessKey = this.configService.get<string>('QINIU_ACCESS_KEY');
    const secretKey = this.configService.get<string>('QINIU_SECRET_KEY');
    this.mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    this.config = new qiniu.conf.Config();
    this.config.zone = (qiniu.zone as any)[this.configService.get<string>('QINIU_ZONE') || "Zone_z2"];
    this.bucketManager = new qiniu.rs.BucketManager(this.mac, this.config);
  }

  // 生成上传凭证
  public createUploadToken(bucketName?: string, key?: string): string {
    bucketName = bucketName || this.configService.get<string>('QINIU_BUCKET');
    const options = {
      scope: bucketName,
      expires: 7200, // 默认凭证过期时间为2小时
    };
    if (key) {
      options['scope'] = `${bucketName}:${key}`;
    }
    const putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(this.mac);
  }

  // 拿到文件上传的url(前端发过来的)
  async saveUploadedUrl(url: string): Promise<{ code: number; message: string; url: string; isUploaded: boolean }> {
    return {
      url,
      code: 200,
      message: "上传成功!",
      isUploaded: true
    };
  }

  getPrivateDownloadUrl(key: string) {
    const mac = new qiniu.auth.digest.Mac(
      this.configService.get<string>('QINIU_ACCESS_KEY'),
      this.configService.get<string>('QINIU_SECRET_KEY')
    );
    const config = new qiniu.conf.Config();
    const bucketManager = new qiniu.rs.BucketManager(mac, config);

    const domain = 'st1s29d0j.hn-bkt.clouddn.com'; // 七牛云的oss的"文件管理"右上角的:"外链域名"
    const deadline = Math.floor(Date.now() / 1000) + 3600; // 设置过期时间为1小时后

    const privateUrl = bucketManager.privateDownloadUrl(domain, key, deadline);

    return { url: privateUrl, code: 200, message: "七牛云资源链接获取成功!" };
  }
}